package com.hpin.fansea.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hpin.fansea.R;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.LogUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * 注册页面
 * Created by Aaron on 15/9/8.
 */
public class RegistActivity extends BaseActivity {

    private EditText et_phone;
    private EditText et_code;

    private TextView tv_verification;
    private Button btn_next;

    private String phone_num;// 手机号
    private String code_num;// 验证码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_regist);

        mApplication.addActivity(this);

        initView();
    }

    private void initView() {

        et_phone = (EditText) findViewById(R.id.et_regist_phone);
        et_code = (EditText) findViewById(R.id.et_regist_code);

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.registe));

        tv_verification = (TextView) findViewById(R.id.btn_register_verification);
        btn_next = (Button) findViewById(R.id.btn_next);
        iv_agree = (ImageView) findViewById(R.id.iv_agree);
        iv_agree.setSelected(true);
        tv_agree_show_detail = (TextView) findViewById(R.id.tv_agree_show_detail);
        tv_agree_show_detail.setText(Html.fromHtml("<u>" + "注册协议" + "</u>"));

        iv_left.setOnClickListener(this);
        iv_agree.setOnClickListener(this);
        tv_verification.setOnClickListener(this);
        btn_next.setOnClickListener(this);
        tv_agree_show_detail.setOnClickListener(this);

    }

    /**
     * 获取验证码
     */
    private void checkVer() {

        if (!CommonUtils.isNetworkAvailable(getApplicationContext())) {
            Toast.makeText(this, "网络请求失败，请检查您的网络设置", Toast.LENGTH_LONG).show();
            return;
        }

        phone_num = et_phone.getText().toString();
        if (CommonUtils.isNull(phone_num) || !CommonUtils.isPhone(phone_num)) {
            Toast.makeText(this, "请填写正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        //倒计时
        countDown();

        //获取验证码
        getSms();

    }

    /**
     * 下一步
     */
    private void next() {

        phone_num = et_phone.getText().toString().trim();
        code_num = et_code.getText().toString().trim();

        if (!CommonUtils.isNetworkAvailable(getApplicationContext())) {
            Toast.makeText(this, "网络请求失败，请检查您的网络设置", Toast.LENGTH_LONG).show();
            return;
        }

        if (CommonUtils.isNull(phone_num) || !CommonUtils.isPhone(phone_num)) {
            Toast.makeText(this, "请填写正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (CommonUtils.isNull(code_num)) {
            Toast.makeText(this, "请填写验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!iv_agree.isSelected()) {
            return;
        }

        //提交验证
        SMSSDK.submitVerificationCode("86", et_phone.getText().toString().trim(), et_code.getText().toString().trim());

    }

    private ImageView iv_agree;
    private TextView tv_agree_show_detail;

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register_verification:// 获取验证码按钮

                checkVer();
                break;

            case R.id.btn_next: // 下一步

                next();
                break;

            case R.id.iv_left:// 返回

                finish();
                break;

            case R.id.tv_agree_show_detail://查看协议详情

                Intent intent = new Intent(this, AgreementDetailActivity.class);
                startActivity(intent);

                break;
            case R.id.iv_agree://是否同意协议的按钮

                iv_agree.setSelected(!iv_agree.isSelected());

                break;

            default:
                break;
        }
    }

    /**
     * 倒计时
     */
    private void countDown() {

        tv_verification.setClickable(false);
        tv_verification.setEnabled(false);
        if (executor == null) {
            executor = Executors.newSingleThreadExecutor();
        }

        tv_verification.setText(currentTime + " 秒");
        for (int i = 0; i < 60; i++) {

            executor.execute(new Runnable() {

                @Override
                public void run() {

                    SystemClock.sleep(1000);

                    changeTime();
                }
            });

        }

    }

    private int currentTime = 60;
    private ExecutorService executor;
    private boolean ready;

    /**
     * 改变界面时间
     */
    private void changeTime() {
        runOnUiThread(new Runnable() {
            public void run() {

                if (currentTime == 1) {
                    currentTime = 60;
                    tv_verification.setText(getResources().getString(R.string.get_code));
                    tv_verification.setClickable(true);
                    tv_verification.setEnabled(true);

                } else {
                    tv_verification.setText(--currentTime + " 秒");
                }
            }
        });
    }

    private void getSms() {

        EventHandler eventHandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
//                show.dismiss();
                if (result == SMSSDK.RESULT_COMPLETE) {

                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码验证成功
                        LogUtil.d("sms", "==========提交验证码成功 =========");

                        // 跳转到填写资料页
                        Intent intent = new Intent(RegistActivity.this, RegistInformationActivity.class);
                        intent.putExtra("phone_num", phone_num);
                        intent.putExtra("code_num", code_num);
                        startActivity(intent);

                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        LogUtil.d("sms", "==========获取验证码成功 =========");

                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                } else {
                    //验证失败
                    showToast("验证码错误");
                }
            }
        };

        // 注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
        //提交发送短信的请求
        SMSSDK.getVerificationCode("86", et_phone.getText().toString().trim());
        ready = true;

    }

    protected void onDestroy() {
        if (ready) {
            // 销毁回调监听接口
            SMSSDK.unregisterAllEventHandler();
        }
        super.onDestroy();
    }

}
